package com.xu.cloud.common.advice;

import com.xu.cloud.common.advice.annotation.RespEncrypt;
import com.xu.cloud.common.constant.CryptConstant;
import com.xu.cloud.common.constant.OrderConstant;
import com.xu.cloud.common.pojo.http.resp.EncryptResponse;
import com.xu.cloud.common.processor.DecryptionConfigurationPropertyHelper;
import com.xu.cloud.common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 响应体加密后置通知处理器
 *
 * @author xuguan
 * @since 2024/9/2
 */
@Order(OrderConstant.RESPONSE_BODY_ENCRYPT_ADVICE_ORDER)
@RestControllerAdvice
public class ResponseBodyEncryptAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private Environment environment;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.hasMethodAnnotation(RespEncrypt.class)
                || Objects.nonNull(AnnotationUtils.findAnnotation(returnType.getContainingClass(), RespEncrypt.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        final String encryptionKey = environment.getProperty(CryptConstant.ENCRYPTION_KEY_PROPERTY_NAME);
        if (encryptionKey == null) {
            throw new IllegalArgumentException("encryption.key is not set");
        }

        if (body == null) {
            return null;
        } else {
            final EncryptResponse encryptResponse = new EncryptResponse();
            encryptResponse.setEncryptData(DecryptionConfigurationPropertyHelper.encryptionProperty(JsonUtil.toJsonString(body), encryptionKey));
            return encryptResponse;
        }
    }
}
